package com.song.JavaThread_day07.ch7_6;

import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyScheduledTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V>{
	
	
	public MyScheduledTask(Runnable runnable, V result ,RunnableScheduledFuture<V> task , ScheduledThreadPoolExecutor executor) {
		super(runnable, result);
		// TODO Auto-generated constructor stub
		this.task =task;
		this.executor = executor;
	}

	private RunnableScheduledFuture<V> task;
	
	private ScheduledThreadPoolExecutor executor;
	
	private long period;
	
	private long startDate;

	@Override
	public long getDelay(TimeUnit unit) {
		if(!isPeriodic())
			return task.getDelay(unit);
		else{
			if(startDate==0)
				return task.getDelay(unit);
			else{
				Date now = new Date();
				long delay = startDate -now.getTime();
				return unit.convert(delay, TimeUnit.MILLISECONDS);
			}
		}
	}

	@Override
	public int compareTo(Delayed o) {
		// TODO Auto-generated method stub
		return task.compareTo(o);
	}

	@Override
	public boolean isPeriodic() {
		// TODO Auto-generated method stub
		return task.isPeriodic();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		
		if(isPeriodic() && (!executor.isShutdown()))
		{
			Date now = new Date();
			startDate = now.getTime()+period;
			executor.getQueue().add(this);
		}
		System.out.printf("pre-myscheduledtask : %s \n",new Date());
		System.out.printf("MyScheduledTask : is periodic: %s\n ",isPeriodic());
		super.runAndReset();
		System.out.printf("Post_MyScheduledTask : %s\n" , new Date());
	}

	public long getPeriod() {
		return period;
	}

	public void setPeriod(long period) {
		this.period = period;
	}
	
	
	
}
